importJS("libs/jeasyui-181/locale/easyui-lang-zh_CN.js"); //easyui汉化
importJS("libs/request.js?t=" + new Date().getTime());
importJS("libs/jEasyUIPlus.js?t=" + new Date().getTime());
//importJS("libs/viewUtil.js");
importJS("libs/i18n.js");


/*获取路径-libs前绝对路径*/
function getPath() {
    var $_js = document.scripts;
    var $_jsPath;

    for (var i = $_js.length; i > 0; i--) {
        if ($_js[i - 1].src.indexOf("thUtil.js") > -1) {
            $_jsPath = $_js[i - 1].src.substring(0, $_js[i - 1].src.lastIndexOf("/libs/") + 1);
        }
    }
    return $_jsPath;
}
/*引用js文件*/
function importJS($url, $onComplete) {
    var $_path = getPath();
    var $_onload = "";

    if ($onComplete)
        $_onload = 'onload="' + $onComplete + '()" onreadystatechange="eval($(this).attr(\'onload\'));"';
    if ($url.indexOf("http://") != -1)
        document.write('<script type="text/javascript" src="' + $url + '" ' + $_onload + '></scri' + 'pt>');
    else
        document.write('<script type="text/javascript" src="' + $_path + $url + '" ' + $_onload + '></scri' + 'pt>');
}

/**
 * js工具类
 */
var Tools = {};
//storage存储
Tools.setItem = function ($id, $value) {
    var $_str = JSON.stringify($value);
    localStorage.setItem($id, $_str);
};
//storage读取
Tools.getItem = function ($id) {
    var $_value;
    var $_str = localStorage.getItem($id);
    if ($_str != null || $_str != "") {
        try {
            $_value = JSON.parse($_str);
        } catch (e) {
            $_value = $_str;
        }
    }
    return $_value
};
//storage移除
Tools.removeItem = function ($id) {
    localStorage.removeItem($id);
};
//storage清除
Tools.clearItem = function () {
    localStorage.clear();
};

Tools.cookie = {
    setItem: function setCookie(name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";path=/;expires=" + exdate.toGMTString());
    },
    getItem: function getCookie(name) {
        var name = escape(name);
        var allcookies = document.cookie;
        name += "=";
        var pos = allcookies.indexOf(name);
        if (pos != -1) {
            var start = pos + name.length;
            var end = allcookies.indexOf(";", start);
            if (end == -1) {
                end = allcookies.length;
            }
            var value = allcookies.substring(start, end);
            return unescape(value);
        } else {
            return null;
        }

    }
}

Tools.json = {
    parse: function (jsonstr) {
        return JSON.parse(jsonstr); //可以将json字符串转换成json对象
    },
    stringify: function (jsonobj) {
        return JSON.stringify(jsonobj); //可以将json对象转换成json对符串 
    },
    isJSON: function (str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }

            } catch (e) {
                return false;
            }
        }
    },
    findTextById: function (json, id) {
        var text = '';
        for (var i = 0; i < json.length; i++) {
            if (id == json[i].id) {
                text = json[i].text;
                break;
            }
        }
        return text;
    },
    formToJson: function (data) {
        var obj = {};
        $.each(data, function (i, v) {
            obj[v.name] = v.value;
        })
        return obj;
    },
    upperJSONKey: function (jsonObj) {
        if (jsonObj.length == undefined) {
            for (var key in jsonObj) {
                if (jsonObj[key] != null && jsonObj[key].length) {
                    Tools.json.upperJSONKey(jsonObj[key]);
                }
                if (Tools.json.easyui(key)) {
                    jsonObj[key] = jsonObj[key];
                }
                else {
                    jsonObj[key.toUpperCase()] = jsonObj[key];
                    delete (jsonObj[key]);
                }
            }
            return jsonObj;
        }
        else {
            if (jsonObj) {

                //判断是不是数组对象
                if (jsonObj instanceof Array) {
                    for (var i = 0; i < jsonObj.length; i++) {
                        if (Tools.json.easyui(key)) {
                            jsonObj[key] = jsonObj[key];
                        }
                        else {
                            Tools.json.upperJSONKey(jsonObj[i]);
                        }
                    }
                }
            }
            return jsonObj;
        }
    },
    easyui: function (name) {
        var arr = new Array('children', 'rows', 'total');
        var result = false;

        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (item == name) {
                result = true;
                break;
            }
        }
        return result;
    },
    valuesToJSON: function (args) {
        var json = [];
        for (var i = 0; i < args.length; i++) {
            json.push(args[i]);
        }
        return json;
    }
}

/**
 *
 * @param fileObj 文件对象
 * @param success 结果回调
 */
Tools.imgTobase64 = function(fileObj, success) {
    var allowExtention = ".jpg,.bmp,.gif,.png";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;  
    var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
    var browserVersion = window.navigator.userAgent.toUpperCase();
    if (allowExtention.indexOf(extention) > -1) {
        if (fileObj.files) {//HTML5实现预览，兼容chrome、火狐7+等  
            if (window.FileReader) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    success(e.target.result);
                }
                reader.readAsDataURL(fileObj.files[0]);
            } else if (browserVersion.indexOf("SAFARI") > -1) {
                alert("不支持Safari6.0以下浏览器的图片预览!");
            }
        } else if (browserVersion.indexOf("MSIE") > -1) {
            if (browserVersion.indexOf("MSIE 6") > -1) {//ie6  
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
            } else {//ie[7-9]  
                fileObj.select();
                if (browserVersion.indexOf("MSIE 9") > -1)
                    fileObj.blur();//不加上document.selection.createRange().text在ie9会拒绝访问  

                success(document.selection.createRange().text);
            }
        } else if (browserVersion.indexOf("FIREFOX") > -1) {
            //firefox
            var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
            if (firefoxVersion < 7) {
                //firefox7以下版本
                var url = fileObj.files[0].getAsDataURL();
                success(url);
            } else {
                //firefox7.0+
                var url = window.URL.createObjectURL(fileObj.files[0]);
                success(url);
            }
        } else {
            var url = fileObj.value;
            success(url);
        }
    } else {
        Tools.alert("仅支持" + allowExtention + "为后缀名的文件!");
        fileObj.value = "";//清空选中文件  
        if (browserVersion.indexOf("MSIE") > -1) {
            fileObj.select();
            document.selection.clear();
        }
        fileObj.outerHTML = fileObj.outerHTML;
    }
}

Tools.date = {
    addDay: function (date,num) {
        var dd = date;
        dd.setDate(dd.getDate() + num); //获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1; //获取当前月份的日期
        m = m < 10 ? '0' + m : m;
        var d = dd.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + "-" + m + "-" + d;
    },
    formatDate : function (date, fmt) {
        date = !date ? new Date() : date;
        date = typeof date == 'number' ? new Date(date) : date;
        fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
        var obj =
            {
                'y': date.getFullYear(), // 年份，注意必须用getFullYear
                'M': date.getMonth() + 1, // 月份，注意是从0-11
                'd': date.getDate(), // 日期
                'q': Math.floor((date.getMonth() + 3) / 3), // 季度
                'w': date.getDay(), // 星期，注意是0-6
                'H': date.getHours(), // 24小时制
                'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
                'm': date.getMinutes(), // 分钟
                's': date.getSeconds(), // 秒
                'S': date.getMilliseconds() // 毫秒
            };
        var week = ['天', '一', '二', '三', '四', '五', '六'];
        for (var i in obj) {
            fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
                var val = obj[i] + '';
                if (i == 'w')
                    return (m.length > 2 ? '星期' : '周') + week[val];
                for (var j = 0, len = val.length; j < m.length - len; j++)
                    val = '0' + val;
                return m.length == 1 ? val : val.substring(val.length - m.length);
            });
        }
        return fmt;
    }
}

Tools.addDate = function (date, days) {
    if (days == undefined || days == '') {
        days = 1;
    }
    var date = new Date(date);
    date.setDate(date.getDate() + days);
    var month = date.getMonth() + 1;
    var day = date.getDate();
    return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
}

/**
 * 控制字符串长度，超出部分省略号代替
 * @param {String} str
 * @param {Number} len
 */
Tools.strEllipse = function (str, len) {
    if (str.length < len)
        return str;
    var newStr = str.substr(0, len) + '…';
    return newStr;
};

/********json操作********/
Tools.jsonCom = {
    //将json转成url参数
    jsonToUrlParam: function (param, key) {
        var my = this;
        var paramStr = "";
        if (param instanceof String || param instanceof Number || param instanceof Boolean || param == null) {
            paramStr += "&" + key + "=" + encodeURIComponent(param);
        } else {
            $.each(param, function (i) {
                var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
                paramStr += '&' + my.jsonToUrlParam(this, k);
            });
        }
        return paramStr.substr(1);
    },
    //将url参数转成json
    urlParamToJson: function (url) {
        if (url.indexOf("?") > -1) {
            var string_a = url.split('?')[1];
            if (string_a.length > 0) {
                var string = string_a.split('&');
                var res = {};
                for (var i = 0; i < string.length; i++) {
                    var str = string[i].split('=');
                    res[str[0]] = decodeURIComponent(str[1]);
                }
                return res;
            } else
                return null;
        } else
            return null;
    }
};
/********正则校验********/
Tools.validaCom = {
    //验证正则
    _regex: {
        mobile: /1[3|4|5|7|8]\d{9}/,
        isIDCard: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
        email: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/,
    },
    //验证手机
    isMobile: function (txt) {
        return this._regex.mobile.test(txt);
    },
    //验证邮箱
    isEmail: function (txt) {
        return this._regex.email.test(txt);
    },
    //身份证验证
    isIDCard: function (txt) {
        return this._regex.isIDCard.test(txt);
    }
};


Tools.uuid = function () {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

/**
* 弹出框的封装
* @param {any} message 弹出的消息内容
* @param {any} method  弹出消息点击确定后，执行后续的事件
*/
Tools.alert = function (message, method) {
    if (method) {
      window.parent.$.messager.alert({ title: lan.message.alert.title, msg: message, fn: method });
    }
    else {
      window.parent.$.messager.alert({ title: lan.message.alert.title, msg: message });
    }
}

Tools.show = function (message) {
    var tips = '<div class="tips-template">'+message+'</div>';
    $('body').append(tips);
    setTimeout(function () {
        $('.tips-template').slideUp();
        setTimeout(function () {
            $('.tips-template').remove();
        }, 200);
    }, 2000);
}

Tools.confirm = function (message, method) {
    if (method) {
      window.parent.$.messager.confirm({ title: lan.message.confirm.title, msg: message, fn: method });
    }
    else {
        Tools.alert('没有传入方法');
    }
}

/*
//使用示例:
//url: http://127.0.0.1/demo.jsp?a&page=2&b=dd&c=123&b=dd2
UrlParm.parm(0)             // 结果:  "";
UrlParm.parm('a')           // 结果:  "";
UrlParm.parm('page')        // 结果:  "2";
UrlParm.parm(1)             // 结果:  "2";
UrlParm.parm("b")           // 结果:  "dd";
UrlParm.parmValues("b")     // 结果:  ["dd","dd2"];
UrlParm.hasParm("b")        // 结果:  true;
UrlParm.hasParm("x")        // 结果:  false;
UrlParm.parmMap()           // 结果:  {a:[""],page:[2],b:["dd","dd2"],c:["123"]};
*/
UrlParm = function () { // url参数
    var data, index;
    (function init() {
        data = [];
        index = {};
        var u = window.location.search.substr(1);
        if (u != '') {
            var parms = decodeURIComponent(u).split('&');
            for (var i = 0, len = parms.length; i < len; i++) {
                if (parms[i] != '') {
                    var p = parms[i].split("=");
                    if (p.length == 1 || (p.length == 2 && p[1] == '')) {
                        data.push(['']);
                        index[p[0]] = data.length - 1;
                    } else if (typeof (p[0]) == 'undefined' || p[0] == '') {
                        data[0] = [p[1]];
                    } else if (typeof (index[p[0]]) == 'undefined') { // c=aaa
                        data.push([p[1]]);
                        index[p[0]] = data.length - 1;
                    } else {// c=aaa
                        data[index[p[0]]].push(p[1]);
                    }
                }
            }
        }
    })();
    return {
        //window.location.search.substr(1)
        urlParm: function () {
            try { return window.location.search.substr(1); }
            catch (e) { }
        },
        // 获得参数,类似request.getParameter()
        parm: function (o) { // o: 参数名或者参数次序
            try {
                return (typeof (o) == 'number' ? data[o][0] : data[index[o]][0]);
            } catch (e) {
            }
        },
        //获得参数组, 类似request.getParameterValues()
        parmValues: function (o) { //  o: 参数名或者参数次序
            try {
                return (typeof (o) == 'number' ? data[o] : data[index[o]]);
            } catch (e) { }
        },
        //是否含有parmName参数
        hasParm: function (parmName) {
            return typeof (parmName) == 'string' ? typeof (index[parmName]) != 'undefined' : false;
        },
        // 获得参数Map ,类似request.getParameterMap()
        parmMap: function () {
            var map = {};
            try {
                for (var p in index) { map[p] = data[index[p]]; }
            } catch (e) { }
            return map;
        },
        //替换URL连接串中的name和value，并返回替换后的URL
        replace: function (name, value) {
            var map = {};
            try {
                for (var p in index) { map[p] = data[index[p]]; }
            } catch (e) { }
            var args = new Array();
            try {
                $.each(map, function (idx, obj) {
                    if (idx == name) {
                        args[args.length] = new Array(name + '=' + value);
                    }
                    else {
                        args[args.length] = new Array(idx + '=' + obj);
                    }
                });
            } catch (e) { }

            return args.join('&');
        }
    }
}();

//js字符串格式化
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

/**
 * 重写Form表单转Json
 * */
$.fn.serializeJson = function () {
    var serializeObj = {};
    var array = this.serializeArray();
    var str = this.serialize();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};

/**
 * jeasyui控件對日期進行格式化
 * @param {any} date
 */
function myformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}
/**
 * jeasyui控件對日期進行格式化
 * @param {any} s
 */
function myparser(s) {
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0], 10);
    var m = parseInt(ss[1], 10);
    var d = parseInt(ss[2], 10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        return new Date(y, m - 1, d);
    } else {
        return new Date();
    }
}